#include "shareondisk.h"
#include <QtPlugin>
#include <QApplication>
#include <QAction>
#include <QProgressDialog>

Q_EXPORT_PLUGIN2(shareondisk, ShareOnDisk)

ShareOnDisk::ShareOnDisk(QObject * parent)
    : QObject(parent)
{
}

ShareOnDisk::~ShareOnDisk()
{
    clear();
}

void ShareOnDisk::setup(PioCore * core)
{
    m_core = core;
    m_action = new QAction(tr("share on disk"), this);
    m_action->setCheckable(true);
    connect(m_action, SIGNAL(triggered(bool)), this, SLOT(shareSelection(bool)));
    m_core->toolbar()->addAction(m_action);
    m_path = m_core->settings().value("share_on_disk_path", "C:\\Users\\Public\\Pictures").toString();
}

QStringList ShareOnDisk::licenseInfo()
{
    return QStringList();
}

void ShareOnDisk::shareSelection(bool share)
{
    clear();

    if(share) {
        QList<MediaItemPtr> sel = m_core->selection();
        QProgressDialog progress(tr("Preparing images..."), tr("Cancel"), 0, sel.size(), m_core->mainwindow());
        progress.setWindowModality(Qt::WindowModal);

        for(int i = 0; i < sel.size(); i++) {
            progress.setValue(i);
            if(progress.wasCanceled()) {
                clear();
                m_action->setChecked(false);
                return;
            }
            QImage image = m_core->load(sel[i]->metadata().filename, QSize(1920, 1080));

            // save file
            QString filename = QString("%1/shared-%2.jpg").arg(m_path).arg(i, 5, 10, QChar('0'));
            image.save(filename);
            m_files.append(filename);
        }
        progress.setValue(sel.size());
    }
}

void ShareOnDisk::clear()
{
    foreach(QString file, m_files) {
        QFile::remove(file);
    }
    m_files.clear();
}
